package com.hdw.cms.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hdw.basic.model.Pager;
import com.hdw.basic.model.SystemContext;
import com.hdw.cms.model.Attachment;
import com.hdw.cms.model.Channel;
import com.hdw.cms.model.ChannelType;
import com.hdw.cms.model.Topic;
import com.hdw.cms.service.AttachmentService;
import com.hdw.cms.service.ChannelService;
import com.hdw.cms.service.KeywordService;
import com.hdw.cms.service.TopicService;
import com.hdw.cms.web.BaseInfoUtil;

@Controller
public class IndexController {

	@Resource(name = "channelService")
	private ChannelService channelService;

	@Resource(name = "topicService")
	private TopicService topicService;

	@Resource(name = "attachmentService")
	private AttachmentService attachmentService;

	@Resource(name = "keywordService")
	private KeywordService keywordService;

	@RequestMapping({ "/.do", "/index.do" })
	public String index(Model model) {
		model.addAttribute("baseInfo", BaseInfoUtil.getInstacne().read());
		return "index/index";
	}

	@RequestMapping("/test.do")
	public String index2(Model model) {
		model.addAttribute("baseInfo", BaseInfoUtil.getInstacne().read());
		return "back/admin/index";
	}

	@RequestMapping("/channel/{cid}.do")
	public String showChannel(@PathVariable int cid, Model model, HttpServletRequest req,
			HttpSession session) throws IOException {
		Channel c = channelService.getFamfily(cid);
		Channel pc = null;
		if (c != null) {
			if (c.getType() == ChannelType.NAV_CHANNEL) {
				pc = c;
				// 如果是导航栏目，需要获取该栏目中的第一个栏目
				c = channelService.loadFirstChannelByNav(c.getId());
				// if ((c.getType() == ChannelType.TOPIC_PROIMG) && (c.getType()
				// !=
				// ChannelType.TOPIC_LIST)) {
				// 显示图片的用产品图片代替了
				// System.out.println(c.getType());
				// SystemContext.setPageSize(16);
				// SystemContext.setSort("a.topic.publishDate");
				// SystemContext.setOrder("desc");
				// SystemContext.removeSort();
				// SystemContext.removeOrder();
				// model.addAttribute("pc", pc);
				// model.addAttribute("cs",
				// channelService.listUseChannelByParent(pc.getId()));
				// model.addAttribute("channel", c);
				// return "index/channel_pic";
				// }
			}
			else {
				pc = c.getParent();
			}
			// System.out.println(c.getType()==ChannelType.TOPIC_LIST);
			// System.out.println(c.getType());
			// 如果是文章栏目或者是文章内容栏目直接显示文章
			if (c.getType() == ChannelType.TOPIC_CONTENT) {
				if (c.getChildren().size() > 0) {
					// 判断栏目是否加密
					// 在前台判断是否是来自二级导航
					if (c.getisConList() == 1) {
						model.addAttribute("ff", "ff");
					}
					c = c.getChildren().get(0);
				}
				if (c.getvisitPassword() != null && !"".equals(c.getvisitPassword())) {
					String visitPassword = req.getParameter("visitPassword");
					if (req.getParameter("visitPassword") == null
							&& session.getAttribute("visitPassword") == null) {
						model.addAttribute("encryption", "encryption");
					}
					else if (!c.getvisitPassword().equals(visitPassword)
							&& !c.getvisitPassword()
									.equals(session.getAttribute("visitPassword"))) {
						model.addAttribute("visitError", "对不起，您的访问密码错误");
						model.addAttribute("encryption", "encryption");
					}
					else {
						session.setAttribute("visitPassword", c.getvisitPassword());
					}
				}
				if (channelService.findGrandFather(c.getId()) != null) {
					model.addAttribute("channel", c);// 获得当前栏目
					model.addAttribute("cc",
							channelService.listByParent(c.getParent().getId()));// 获得3级栏目
					Channel grandFather = channelService.findGrandFather(c.getId());// 获得一级栏目
					model.addAttribute("cs", grandFather.getChildren());// 获得2级栏目
					model.addAttribute("pc", grandFather);
				}
				else {
					model.addAttribute("pc", pc);
					model.addAttribute("cs",
							channelService.listUseChannelByParent(pc.getId()));
					model.addAttribute("channel", c);
				}
				SystemContext.removeSort();
				SystemContext.removeOrder();
				Topic t = new Topic();
				if (topicService.loadLastedTopicByColumn(c.getId()) != null) {
					t = topicService.load(
							topicService.loadLastedTopicByColumn(c.getId()).getId());
					String keywords = t.getKeyword();
					model.addAttribute("topic", t);
					if (keywords == null || "".equals(keywords.trim())
							|| "\\|".equals(keywords.trim())) {
						model.addAttribute("hasKey", false);
					}
					else {
						String[] kws = keywords.split("\\|");
						model.addAttribute("hasKey", true);
						model.addAttribute("kws", kws);
					}
				}
				else {
					t = null;
				}
				return "index/channel";
			} // 如果是图片栏目，要获取这个图片中的
				// else if (c.getType() == ChannelType.People_CONTENT) {
				// resp.sendRedirect(req.getContextPath() + "/people/"
				// + topicService.loadLastedTopicByColumn(cid).getId());
				// } 显示人员的注释了
				// else if (c.getType() == ChannelType.TOPIC_PROIMG) {
				// SystemContext.setPageSize(16);
				// SystemContext.setSort("a.topic.publishDate");
				// SystemContext.setOrder("desc");
				// } 显示产品图片的先注释
			else if (c.getType() == ChannelType.TOPIC_LIST) {
				SystemContext.setSort("t.publishDate");
				SystemContext.setOrder("desc");
				// System.out.println(c.getType());
				model.addAttribute("datas", topicService.find(c.getId(), null, 1));
			}
			else if (c.getType() == ChannelType.TOPIC_PROIMG) {
				model.addAttribute("pc", pc);
				model.addAttribute("cs",
						channelService.listUseChannelByParent(pc.getId()));
				SystemContext.setPageSize(9);
				SystemContext.setSort("a.proPos");
				SystemContext.setOrder("asc");
				model.addAttribute("proPic", attachmentService.findProPic(c.getId()));
				model.addAttribute("channel", c);
				return "index/proList";
			}
			else if (c.getType() == ChannelType.VIDEO_LIST) {
				if (c.getvisitPassword() != null && !"".equals(c.getvisitPassword())) {
					String visitPassword = req.getParameter("visitPassword");
					if (req.getParameter("visitPassword") == null
							&& session.getAttribute("vvisitPassword") == null) {
						model.addAttribute("encryption", "encryption");
					}
					else if (!c.getvisitPassword().equals(visitPassword)
							&& !c.getvisitPassword()
									.equals(session.getAttribute("vvisitPassword"))) {
						model.addAttribute("visitError", "对不起，您的访问密码错误");
						model.addAttribute("encryption", "encryption");
					}
					else {
						session.setAttribute("vvisitPassword", c.getvisitPassword());
					}
				}
				model.addAttribute("channel", c);// 获得当前栏目
				model.addAttribute("cc",
						channelService.listByParent(c.getParent().getId()));// 获得3级栏目
				if (channelService.findGrandFather(c.getId()) != null) {
					Channel grandFather = channelService.findGrandFather(c.getId());// 获得一级栏目
					model.addAttribute("cs", grandFather.getChildren());// 获得2级栏目
					model.addAttribute("pc", grandFather);
				}
				SystemContext.setPageSize(12);
				SystemContext.setSort("a.vdoPos");
				SystemContext.setOrder("asc");
				model.addAttribute("video", attachmentService.findVideo(c.getId()));
				return "index/videoList";
			}
			SystemContext.removeSort();
			SystemContext.removeOrder();
			model.addAttribute("pc", pc);
			model.addAttribute("cs", channelService.listUseChannelByParent(pc.getId()));
			model.addAttribute("channel", c);
			if (c.getType() == ChannelType.TOPIC_LIST) {
				return "index/channel";
			}
			else {
				return "index/channel_pic";
			}
		}
		else {
			return "not find";
		}
	}

	@RequestMapping("/showVideo/{vid}.do")
	public String showVideo(@PathVariable int vid, Model model, HttpSession session) {
		Attachment video = attachmentService.loadVideo(vid);
		String vvisitPassword = channelService.load(video.getProTypeId())
				.getvisitPassword();
		if (session.getAttribute("vvisitPassword") == null && vvisitPassword != null
				&& !"".equals(vvisitPassword)) {
			return "";
		}
		List<Attachment> videoAll = attachmentService
				.findVideoBytype(video.getProTypeId());
		model.addAttribute("video", video);
		model.addAttribute("videoAll", videoAll);
		model.addAttribute("vc", channelService.load(video.getProTypeId()));
		return "index/showVideo";
	}

	// @RequestMapping("/people/{tid}")
	// public String showTopicPeople(@PathVariable int tid, Model model) {
	// Topic t = topicService.load(tid);
	// model.addAttribute("topic", t);
	// return "people/teacher";
	// }

	@RequestMapping("/showProPic/{proPicId}.do")
	public String showProPic(@PathVariable Integer proPicId, Model model) {
		Attachment pic = attachmentService.load(proPicId);
		Channel c = channelService.load(pic.getProTypeId());
		Channel pc = c.getParent();
		model.addAttribute("pc", pc);
		model.addAttribute("c", c);
		model.addAttribute("proPic", pic);
		return "index/showProPic";
	}

	@RequestMapping("/topic/{tid}.do")
	public String showTopic(@PathVariable int tid, Model model) {
		Topic t = topicService.load(tid);
		String keywords = t.getKeyword();
		Channel fc = channelService.finFatherWithBrother(t.getChannel().getId());
		if (fc != null)
			model.addAttribute("fc", fc);
		model.addAttribute("topic", t);
		if (keywords == null || "".equals(keywords.trim())
				|| "\\|".equals(keywords.trim())) {
			model.addAttribute("hasKey", false);
		}
		else {
			String[] kws = keywords.split("\\|");
			model.addAttribute("hasKey", true);
			model.addAttribute("kws", kws);
		}
		return "index/topic";
	}

	// 根据内容检索
	@RequestMapping("/search/{con}.do")
	public String search(@PathVariable String con, Model model) {
		SystemContext.setOrder("asc");
		SystemContext.setSort("c.orders");
		model.addAttribute("cs",
				channelService.listChannelByType(ChannelType.NAV_CHANNEL));
		SystemContext.setOrder("desc");
		SystemContext.setSort("t.publishDate");
		/************ 在搜索出来的内容上高亮显示检索内容 ****************************/
		Pager<Topic> topics = topicService.searchTopic(con);
		emp(topics, con);
		/****************************************/
		model.addAttribute("datas", topics);
		model.addAttribute("con", con);
		return "index/searchresult";
	}

	@RequestMapping("/searchPro/{attName}.do")
	public String searchPro(@PathVariable String attName, Model model) {
		SystemContext.setPageSize(6);
		SystemContext.setSort("a.id");
		SystemContext.setOrder("desc");
		model.addAttribute("proPic", attachmentService.listSearchPro(attName));
		return "index/searchresult";
	}

	// 根据关键字检索
	@RequestMapping("/keyword/{con}.do")
	public String keyword(@PathVariable String con, Model model) {
		// 根据关键字的最大引用率检索
		model.addAttribute("kws", keywordService.getMaxTimesKeyword(9));
		SystemContext.setOrder("desc");
		SystemContext.setSort("t.publishDate");
		Pager<Topic> topics = topicService.searchTopicByKeyword(con);
		emp(topics, con);
		model.addAttribute("datas", topics);
		model.addAttribute("con", con);
		return "index/keyword";
	}

	// 由于强调高亮显示的文章
	private void emp(Pager<Topic> topics, String con) {
		for (Topic t : topics.getDatas()) {
			if (t.getTitle().contains(con)) {
				String tt = t.getTitle().replaceAll(con,
						"<span class='emp'>" + con + "</span>");
				t.setTitle(tt);
			}
		}
	}

	// 根据关键字检索
	// @RequestMapping("/teacher/{id}")
	// public String Peoplelist(@PathVariable int id, Model model) {
	// Map<Integer, List<People>> dplist = new HashMap<Integer, List<People>>();
	// Pager<Department> alld = this.departmentService.findDepartment();
	// List<Department> alld1 = alld.getDatas();
	// for (Department dep : alld1) {
	// int did = dep.getId();
	// dplist.put(dep.getId(),
	// this.peopleService.listAllDepartmentPeoplesByzhichen(did, id));
	// }
	// model.addAttribute("alld", alld1);
	// model.addAttribute("dplist", dplist);
	// return "people/teacher";
	// }

	//
	// @RequestMapping("/teachershow/{id}")
	// public String PeopleShow(@PathVariable int id, Model model) {
	// model.addAttribute(peopleService.load(id));
	// model.addAttribute("pd", peopleService.listPeopleDepartments(id));
	// return "people/teachershow";
	// }
}
